package com.atguigu.service.impl;

import com.atguigu.entity.BaseBrand;
import com.atguigu.exception.SleepUtils;
import com.atguigu.mapper.BaseBrandMapper;
import com.atguigu.service.BaseBrandService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 品牌表 服务实现类
 * </p>
 *
 * @author zhangqiang
 * @since 2021-08-24
 */
@Service
public class BaseBrandServiceImpl extends ServiceImpl<BaseBrandMapper, BaseBrand> implements BaseBrandService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    //@Override
    public void setNum0() {
        String value = (String)redisTemplate.opsForValue().get("num");
        if(StringUtils.isEmpty(value)){
            redisTemplate.opsForValue().set("num","1");
        }else{
            int num = Integer.parseInt(value);
            //对num进行加1操作
            redisTemplate.opsForValue().set("num",String.valueOf(++num));
        }
    }

    //@Override
    public synchronized void setNum01() {
        String value = (String)redisTemplate.opsForValue().get("num");
        if(StringUtils.isEmpty(value)){
            redisTemplate.opsForValue().set("num","1");
        }else{
            int num = Integer.parseInt(value);
            //对num进行加1操作
            redisTemplate.opsForValue().set("num",String.valueOf(++num));
        }
    }
    private void doBusiness() {
        String value = (String) redisTemplate.opsForValue().get("num");
        if (StringUtils.isEmpty(value)) {
            redisTemplate.opsForValue().set("num", "1");
        } else {
            int num = Integer.parseInt(value);
            //对num进行加1操作
            redisTemplate.opsForValue().set("num", String.valueOf(++num));
        }
    }

    //分布式锁方案一
    //@Override
    public void setNum1() {
        //利用redis的setnx命令
        boolean acquireLock = redisTemplate.opsForValue().setIfAbsent("lock", "ok");
        if(acquireLock){
            //拿到锁 如果doBusiness出现异常异常 锁会一直占用 无法释放
            doBusiness();
            //业务完成之后删除锁
            redisTemplate.delete("lock");
        }else{
            //设置睡眠时间
            SleepUtils.sleepMillis(50);
            //自旋
            setNum();
        }
    }
    //分布式锁方案二
    //@Override
    public void setNum2() {
        //利用redis的setnx命令 该键只能存放3秒钟
        boolean acquireLock = redisTemplate.opsForValue().setIfAbsent("lock", "ok",3, TimeUnit.SECONDS);
        if(acquireLock){
            //拿到锁 如果doBusiness出现异常异常 锁会一直占用 无法释放
            doBusiness();
            //业务完成之后删除锁
            redisTemplate.delete("lock");
        }else{
            //设置睡眠时间
            SleepUtils.sleepMillis(50);
            //自旋
            setNum();
        }
    }
    //分布式锁方案三
    //@Override
    public void setNum3() {
        String uuid = UUID.randomUUID().toString();
        //利用redis的setnx命令 该键只能存放3秒钟
        boolean acquireLock = redisTemplate.opsForValue().setIfAbsent("lock", uuid,3, TimeUnit.SECONDS);
        if(acquireLock){
            //拿到锁 如果doBusiness出现异常异常 锁会一直占用 无法释放
            doBusiness();
            //删除之前判断是否为自己的锁
            String redisUuid =(String) redisTemplate.opsForValue().get("lock");
            if(uuid.equals(redisUuid)){
                //业务完成之后删除锁
                redisTemplate.delete("lock");
            }
        }else{
            //设置睡眠时间
            SleepUtils.sleepMillis(50);
            //自旋
            setNum();
        }
    }

    //分布式锁方案四
    //@Override
    public void setNum4() {
        String uuid = UUID.randomUUID().toString();
        //利用redis的setnx命令 该键只能存放3秒钟
        boolean acquireLock = redisTemplate.opsForValue().setIfAbsent("lock", uuid,3, TimeUnit.SECONDS);
        if(acquireLock){
            //拿到锁 如果doBusiness出现异常异常 锁会一直占用 无法释放
            doBusiness();
            //定义一个脚本
            String luaScript="if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
            DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
            //把脚本封装到redisScript对象中
            redisScript.setScriptText(luaScript);
            //设置执行脚本之后返回上面类型
            redisScript.setResultType(Long.class);
            //准备执行脚本
            redisTemplate.execute(redisScript, Arrays.asList("lock"),uuid);
            /**
             * 上面的一大坨 就是下面代码的改造 把它给原子性了
             * //删除之前判断是否为自己的锁
             * String redisUuid =(String) redisTemplate.opsForValue().get("lock");
             * if(uuid.equals(redisUuid)){
             *     //业务完成之后删除锁
             *     redisTemplate.delete("lock");
             * }
             */
        }else{
            //设置睡眠时间
            SleepUtils.sleepMillis(50);
            //自旋
            setNum();
        }
    }
    //之前加锁
    //@Override
    public void setNum11() {
        RLock lock = redissonClient.getLock("lock");
        lock.lock();
        doBusiness();
        lock.unlock();
    }

    //@Override
    public void setNum22() {
        RLock lock = redissonClient.getLock("lock");
        //超时自动释放锁
        lock.lock(3,TimeUnit.SECONDS);
        doBusiness();
        lock.unlock();
    }
    @Override
    public void setNum()  {
        RLock lock = redissonClient.getLock("lock");
        try {
            boolean acquireLock = lock.tryLock(100, 3, TimeUnit.SECONDS);
            if(acquireLock){
                //拿到锁 如果doBusiness出现异常异常 锁会一直占用 无法释放
                doBusiness();

            }else{
                //设置睡眠时间
                SleepUtils.sleepMillis(50);
                //自旋
                setNum();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }






}
